/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package form;

import core.world.WorldResource;
import io.resource.PackageQueue;
import io.resource.DataPackage;
import io.resource.DataRef;
import io.resource.ResourceDelegate;
import io.resource.TemporaryQueue;
import java.awt.Point;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import renderer.DataTableCheckBoxRenderer;
import renderer.DataTableRenderer;

/**
 *
 * @author Robert A. Cherry
 */
public class ChangeMonitor extends javax.swing.JDialog {

    // Varirable Declaration
    // Java Native Classes
    private DefaultTableModel nonPackagedModel;
    private DefaultTableModel packagedModel;
    // Project Clases
    private FaustEditor editor;
    private ResourceDelegate delegate;
    // End of Variable Declaration

    public ChangeMonitor(FaustEditor editor, ResourceDelegate delegate, boolean modal) {

        //
        super(editor, modal);
        initComponents();

        // 
        this.editor = editor;
        this.delegate = delegate;

        //
        init();
    }

    private void init() {

        // New Table Model
        nonPackagedModel = new DefaultTableModel();
        packagedModel = new DefaultTableModel();

        // New ComboBox Model
        final DefaultComboBoxModel boxModel = new DefaultComboBoxModel();
        boxModel.addElement("Not Packaged Files");
        boxModel.addElement("Packaged Files");

        // Apply to combo model and set default selected
        typeJComboBox.setModel(boxModel);
        typeJComboBox.setSelectedIndex(0);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        resourceJScrollPane = new javax.swing.JScrollPane();
        resourceJTable = new javax.swing.JTable();
        resourceJPanel = new javax.swing.JPanel();
        resourceJLabel = new javax.swing.JLabel();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
        typeJComboBox = new javax.swing.JComboBox();
        buttonJPanel = new javax.swing.JPanel();
        filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
        finishJButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("View Changes");

        resourceJTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        resourceJTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                resourceJTableMouseClicked(evt);
            }
        });
        resourceJScrollPane.setViewportView(resourceJTable);

        resourceJPanel.setLayout(new javax.swing.BoxLayout(resourceJPanel, javax.swing.BoxLayout.LINE_AXIS));

        resourceJLabel.setText("Resource Type:");
        resourceJLabel.setMaximumSize(new java.awt.Dimension(128, 22));
        resourceJLabel.setMinimumSize(new java.awt.Dimension(128, 22));
        resourceJLabel.setPreferredSize(new java.awt.Dimension(128, 22));
        resourceJPanel.add(resourceJLabel);
        resourceJPanel.add(filler1);

        typeJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        typeJComboBox.setMaximumSize(new java.awt.Dimension(128, 22));
        typeJComboBox.setMinimumSize(new java.awt.Dimension(128, 22));
        typeJComboBox.setPreferredSize(new java.awt.Dimension(128, 22));
        typeJComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                typeJComboBoxActionPerformed(evt);
            }
        });
        resourceJPanel.add(typeJComboBox);

        buttonJPanel.setLayout(new javax.swing.BoxLayout(buttonJPanel, javax.swing.BoxLayout.LINE_AXIS));
        buttonJPanel.add(filler2);

        finishJButton.setText("Finished");
        finishJButton.setMaximumSize(new java.awt.Dimension(88, 26));
        finishJButton.setMinimumSize(new java.awt.Dimension(88, 26));
        finishJButton.setPreferredSize(new java.awt.Dimension(88, 26));
        finishJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                finishJButtonActionPerformed(evt);
            }
        });
        buttonJPanel.add(finishJButton);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(resourceJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(resourceJScrollPane)
                    .addComponent(buttonJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(resourceJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(resourceJScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void finishJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_finishJButtonActionPerformed

        // Close the dialog
        setVisible(false);
    }//GEN-LAST:event_finishJButtonActionPerformed

    @SuppressWarnings("ConvertToStringSwitch")
    private void typeJComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeJComboBoxActionPerformed

        // Adjust the content of the reference and if its marked for change
        final String option = String.valueOf(typeJComboBox.getSelectedItem());

        //
        if (option.equals("Not Packaged Files")) {

            int resourceIndex = -1;

            // Grab from the Temporary Queue
            final TemporaryQueue queue = delegate.getTemporaryQueue();

            // The default selection is for temporary edits
            final HashMap<Integer, WorldResource> changes = queue.getChanges();

            //
            final String[] columnNames = {"Perform Change", "Resource"};

            // Our collection array
            final WorldResource[] resources = new WorldResource[changes.size()];

            // Swipe over the entry set
            for (Map.Entry<Integer, WorldResource> set : changes.entrySet()) {

                // Increase the index to properly store
                resourceIndex++;

                // Grab from collection
                resources[resourceIndex] = set.getValue();
            }

            // Data vector
            final Object[][] dataVector = new Object[changes.size()][2];

            // Iterate over the set of plugins
            for (int i = 0; i < dataVector.length; i++) {

                // Grab the matching resource dataPackage
                final WorldResource resource = resources[i];

                // Echo the reference
                final DataRef reference = delegate.echoReference(resource);

                // The entire operation could fail
                if (reference != null) {

                    // Default to reference status
                    dataVector[i][0] = reference.isMarkedForChange();
                    dataVector[i][1] = reference;
                }
            }

            // Set new data vector
            nonPackagedModel.setDataVector(dataVector, columnNames);

            // Apply to JTable
            resourceJTable.setModel(nonPackagedModel);
        } else if (option.equals("Packaged Files")) {

            //
            Object[][] dataVector = null;

            // Column Names
            final String[] columnNames = {"Perform Change", "File"};

            // Method for filling the JTable for altered Data Packages
            final DataPackage[] packages = delegate.getDataPackages();

            // Iterate over all the data packages
            for (int i = 0; i < packages.length; i++) {

                // Grab current package
                final DataPackage dataPackage = packages[i];
                final PackageQueue queue = dataPackage.getQueue();

                //
                int fileIndex = -1;

                // The default selection is for temporary edits
                final HashMap<PackageQueue.Pair, File> changes = queue.getChanges();

                // Our collection array
                final File[] files = new File[changes.size()];

                // Swipe over the entry set
                for (Map.Entry<PackageQueue.Pair, File> set : changes.entrySet()) {

                    // Increase the index to properly store
                    fileIndex++;

                    // Grab from collection
                    files[fileIndex] = set.getValue();
                }

                // Data vector
                dataVector = new Object[changes.size()][2];

                // Iterate over the set of plugins
                for (int j = 0; j < dataVector.length; j++) {

                    // Grab the matching resource dataPackage
                    final File file = files[j];

                    // Check to see if the delegate can match a file to a reference
                    final DataRef reference = delegate.echoFile(file);

                    // Operation could fail if we fail to find the file; which is entirely possible.
                    if (reference != null) {

                        // Default to reference status
                        dataVector[j][0] = reference.isMarkedForChange();
                        dataVector[j][1] = reference;
                    }
                }
            }

            // Set the Data Vector
            packagedModel.setDataVector(dataVector, columnNames);

            // Now apply to JTable
            resourceJTable.setModel(packagedModel);
        }

        // Fixed column width for checkbox column
        final int columnWidth = 128;

        // Change the renderer for the first column to solve for JCheckBox
        final TableColumn checkColumn = resourceJTable.getColumnModel().getColumn(0);
        checkColumn.setCellRenderer(new DataTableCheckBoxRenderer());
        checkColumn.setMaxWidth(columnWidth);
        checkColumn.setPreferredWidth(columnWidth);
        checkColumn.setMinWidth(columnWidth);

        //
        final TableColumn pluginColumn = resourceJTable.getColumnModel().getColumn(1);
        pluginColumn.setCellRenderer(new DataTableRenderer());
    }//GEN-LAST:event_typeJComboBoxActionPerformed

    private void resourceJTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resourceJTableMouseClicked

        // Grab the position
        final Point position = evt.getPoint();

        // Grab the row and column
        final int row = resourceJTable.rowAtPoint(position);
        final int col = resourceJTable.columnAtPoint(position);

        // Row must exist
        if (row > -1 && col > -1) {

            // Only the first column
            if (col == 0) {

                try {

                    // Parse the boolean and switch it
                    final Boolean bool = !Boolean.parseBoolean(String.valueOf(resourceJTable.getValueAt(row, 0)));

                    // Change to opposite
                    resourceJTable.setValueAt(bool, row, 0);

                    // Also change inside of Data Reference
                    final DataRef reference = (DataRef) resourceJTable.getValueAt(row, 1);

                    //
                    if (reference != null) {

                        // Change in the reference as well
                        reference.setMarkedForChange(bool);
                    }
                } catch (NumberFormatException nfe) {
                    //
                }
            }
        }
    }//GEN-LAST:event_resourceJTableMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buttonJPanel;
    private javax.swing.Box.Filler filler1;
    private javax.swing.Box.Filler filler2;
    private javax.swing.JButton finishJButton;
    private javax.swing.JLabel resourceJLabel;
    private javax.swing.JPanel resourceJPanel;
    private javax.swing.JScrollPane resourceJScrollPane;
    private javax.swing.JTable resourceJTable;
    private javax.swing.JComboBox typeJComboBox;
    // End of variables declaration//GEN-END:variables
}
